package com.icngor.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.icngor.dao.BaseDaoI;
import com.icngor.model.TMenu;
import com.icngor.pageModel.Menu;
import com.icngor.service.MenuServiceI;

@Service(value="menuService")
public class MenuServiceImpl implements MenuServiceI {

	private static final Logger logger = Logger.getLogger(MenuServiceImpl.class);
	
	private BaseDaoI<TMenu> menuDao;

	public BaseDaoI<TMenu> getMenuDao() {
		return menuDao;
	}
	@Autowired
	public void setMenuDao(BaseDaoI<TMenu> menuDao) {
		this.menuDao = menuDao;
	}
	
	public List<Menu> getTreeNode(String id){
		ArrayList<Menu> mel = new ArrayList<Menu>();
		String hql ="";
		Map<String,Object> map = new HashMap<String,Object>();
		if(id==null || id.equals("")){
			hql="from TMenu t where t.TMenu is null";
		}else{
			hql = "from TMenu t where t.TMenu.id=:id";
			map.put("id", id);
		}
		List<TMenu> list = menuDao.find(hql,map);
		for(TMenu m:list){
			Menu me = new Menu();
			BeanUtils.copyProperties(m, me, new String[]{"textx"});
			me.setText(m.getTextx());
			Set<TMenu> ms = m.getTMenus();
			if(ms!=null && !ms.isEmpty()){
				me.setState("closed");
			}else{
				me.setState("open");
			}
			mel.add(me);
		}
		
		return mel;
	}
	
	@Override
	public List<Menu> getAllTreeNode() {
		List<Menu> mel = new ArrayList<Menu>();
		String hql ="FROM TMenu";
		
		List<TMenu> list = menuDao.find(hql);
		for(TMenu m:list){
			Menu me = new Menu();
			BeanUtils.copyProperties(m, me, new String[]{"textx"});
			me.setText(m.getTextx());
			TMenu tm = m.getTMenu();
			if(tm!=null){
				me.setPid(tm.getId());
			}
			Map<String,Object> attributes = new HashMap<String,Object>();
			attributes.put("url", m.getUrl());
			me.setAttributes(attributes);
			mel.add(me);
		}
		
		return mel;
	}
	
}
